<template>
    <el-dialog v-model="visible" width="60%" draggable="true" :close-on-click-modal="false" append-to-body="true">
        <template #title>
            <span class="h5">
                {{ form.table_id ? '编辑' : '创建' }}数据表
            </span>
        </template>
        <div class="table-structure">
            <el-form label-width="60px" label-postion="right" :model="form" :rules="rules" ref="formRef"
                @submit.native.prevent="handleSubmit">
                <el-form-item label="名称" prop="title">
                    <el-input @input="onTitleChange" show-word-limit maxlength="32" clearable v-model="form.title"
                        placeholder="请输入表中文名称"></el-input>
                </el-form-item>
                <el-form-item label="标识" prop="name">
                    <el-input clearable @dblclick="form._name_edit = false" show-word-limit maxlength="32"
                        placeholder="请输入表标识，为设置时系统自动生成" v-if="form._name_edit" v-model="form.name"></el-input>
                    <span v-if="!form._name_edit" @dblclick="form._name_edit = true">
                        {{ form.name ? form.name : '输入名称后自动生成' }}
                    </span>

                </el-form-item>
                <el-form-item label="用途" prop="description">
                    <el-input type="textarea" rows="6" v-model="form.description" show-word-limit maxlength="100"
                        placeholder="请输入表用途" clearable></el-input>
                </el-form-item>
                <el-form-item label="预置字段" prop="fields">
                    <el-checkbox-group v-model="form.fields" disabled>
                        <el-checkbox-button v-for="field in prefabFields" :key="field" :label="field.title"
                            :value="field.name">
                        </el-checkbox-button>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item>

                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="float-right w-100">
                <el-button :disabled="disabled" type="" @click="cancel">取消</el-button>
                <el-button :disabled="disabled" type="primary" @click="handleSubmit">提交</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { reactive, ref, defineExpose, defineEmits, toRaw } from 'vue';
import $data from "xcore/data";
import $utils from "xcore/utils";
import _ from 'lodash'
const disabled = ref(false)
const form = ref({
    table_id: '',
    title: '',
    name: '',
    description: '',
    fields: ["Id", "created_at", "updated_at"]
});
const prefabFields = {
    Id:
    {
        title: "主键编号",
        name: "id",
        type: "INT",
        source: "DB",
        method: "auto-increment",
        is_nullable: false,
        is_prefab: true,
        sort_id: 0,
    },
    created_at: {
        title: "创建时间",
        name: "created_at",
        type: "TIMESTAMP",
        source: "DB",
        method: "CURRENT_TIMESTAMP",
        default: "current_timestamp",
        param: 1,
        is_nullable: false,
        is_prefab: true,
        sort_id: 1001,
    },
    updated_at: {
        title: "更新时间",
        name: "updated_at",
        type: "TIMESTAMP",
        source: "DB",
        method: "CURRENT_TIMESTAMP",
        default: "current_timestamp",
        param: 2,
        is_nullable: false,
        is_prefab: true,
        sort_id: 1002,
    },
};

const formRef = ref(null);
const visible = ref(false)

const validatePrefields = (rule, value, callback) => {
    if (value.length === 0) {
        callback(new Error('请选择至少一个预置字段'));
    } else {
        callback();
    }
};

const rules = {
    title: [
        { required: true, message: '请输入表名称', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入表标识', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入表用途', trigger: 'blur' }
    ],
    fields: [
        { validator: validatePrefields, trigger: 'change' }
    ]
};


const onTitleChange = () => {
    let fields = $utils.conv.getTableName(form.value.title);
    if (fields.length > 0) {
        form.value.name = fields[0].substring(0, 32)
    }

};

const cancel = () => {
    visible.value = false
    formRef.value.resetFields();
};
const emit = defineEmits(['create'])
const handleSubmit = () => {
    formRef.value.validate((valid) => {
        if (!valid) return false
        let data = _.clone(form.value)
        data.columns = []
        form.value.fields.forEach(field => {
            data.columns.push(prefabFields[field])
        });
        disabled.value = true
        $data.provider.meta.setMetaTable(data).then(res => {
            disabled.value = false
            emit('create', res)
            visible.value = false
            formRef.value.resetFields();
        }).catch(err => {
            disabled.value = false
        })
    })
};
const show = (id) => {
    if (id) {
        $data.provider.meta.getMetaTable(id).then(res => {
            form.value = res
            form.value.fields = ["Id", "created_at", "updated_at"]
        })
    } else {
        form.value = {
            table_id: '',
            title: '',
            name: '',
            description: '',
            fields: ["Id", "created_at", "updated_at"]
        }
    }

    visible.value = true
}
defineExpose({
    show
})
</script>

<style scoped></style>